package com.lingang.project.onlyoffice.service.impl;

import com.lingang.project.onlyoffice.service.MinioService;
import com.lingang.project.onlyoffice.utils.FileUtil;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {
    private final Logger logger = LoggerFactory.getLogger(MinioServiceImpl.class);

    /**
     * minio客户端
     */
    private final MinioClient minioClient;

    @Override
    public String uploadFile(MultipartFile file, String bucket) {
        try {
            StringBuilder sbr = new StringBuilder();
            sbr.append(new SimpleDateFormat("/yyyy/MM/dd/").format(new Date()));
            sbr.append(UUID.randomUUID().toString().replaceAll("-", ""));
            sbr.append(file.getOriginalFilename());
            String result = sbr.toString();
            String contentType = MediaTypeFactory.getMediaType(file.getOriginalFilename()).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(bucket)
                    .object(result)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(contentType)
                    .build();
            minioClient.putObject(putObjectArgs);
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return StringUtils.EMPTY;
        }
    }

    @Override
    public void downloadObject(String bucket, String uri,String filename, String contentType) {
        Assert.isTrue(StringUtils.isNotBlank(bucket),"bucket is blank");
        Assert.isTrue(StringUtils.isNotBlank(uri),"uri is blank");
        Assert.isTrue(StringUtils.isNotBlank(contentType),"contentType is blank");
        Assert.isTrue(StringUtils.isNotBlank(filename),"filename is blank");
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = attributes.getResponse();
            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename,StandardCharsets.UTF_8.name()));
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            InputStream inputStream = minioClient.getObject(GetObjectArgs.builder().object(uri).bucket(bucket).build());
            FileUtil.writeFile(inputStream,response.getOutputStream());
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("设置文件流数据时出现问题===---");
        }
    }

}
